//
//  SJFollowListViewController.m
//  WSL
//
//  Created by CJ on 2017/12/5.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJFollowListViewController.h"
#import "SJMyFollowApi.h"
#import "SJMyFollowedApi.h"
#import "SJCustomLayout.h"
#import "SJWordItem.h"
#import "SJUserInfoItem.h"
#import "SJFollowCell.h"
#import "SJUnFollowPersonApi.h"
#import "SJFollowPersonApi.h"
#import "SJPersonalViewController.h"


@interface SJFollowListViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate>

@property (strong, nonatomic) SJCustomLayout *customLayout;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (nonatomic, strong) UIView *navigationBarView; // 背景

@end

@implementation SJFollowListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}


- (void)dealloc {
    SJLogFunc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    [self loadNewData];
}

- (void)setupUI {
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
}

#pragma mark - getter

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        
        if (self.isFollowed) {
            wordLabel.text = @"关注者";
        } else {
            wordLabel.text = @"关注";
        }
        
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
    }
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (SJCustomLayout *)customLayout{
    
    if (!_customLayout) {
        _customLayout = [[SJCustomLayout alloc] init];
        _customLayout.delegate = self;
        
    }
    return _customLayout;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(SJLayoutFrame(50), 0, 0, 0);
        
        [_collectionView registerClass:[SJFollowCell class] forCellWithReuseIdentifier:NSStringFromClass([SJFollowCell class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    
    return _collectionView;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat w = 8 * SJItemWH + (8 - 1) * SJMargin;
    CGFloat h = 2 * SJItemWH + (2 - 1) * SJMargin;
    CGFloat x = SJMargin;
    CGFloat y = (h + SJMargin) * indexPath.row;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return SJLayoutFrame(10);
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJFollowCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJFollowCell class]) forIndexPath:indexPath];
    
    SJUserInfoItem *userInfo = self.dataArray[indexPath.row];
    
    cell.userInfo = userInfo;
    cell.isMe = self.isMe;
    
    WeakSelf;
    cell.followTap = ^(UICollectionViewCell *cell) {
        
        [weakSelf followTap:cell];
    };
    
    return cell;
}

- (void)followTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    SJUserInfoItem *userInfo = self.dataArray[indexPath.row];
    
    if ([userInfo.st isEqualToString:@"2"]) { // 未关注
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"fid"] = userInfo.ID;
        
        SJFollowPersonApi *api = [[SJFollowPersonApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
                userInfo.st = @"1";
                [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
        
    } else {
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"fid"] = userInfo.ID;
        
        SJUnFollowPersonApi *api = [[SJUnFollowPersonApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
                userInfo.st = @"0";
                [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
        
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJUserInfoItem *userInfo = self.dataArray[indexPath.row];
    
    SJPersonalViewController *personVC = [SJPersonalViewController new];
    SJUserInfoItem *myInfo = [SJUserInfoItem modelWithJSON:[SJUserDefaults objectForKey:SJUserInfo]];
    if ([myInfo.ID isEqualToString:userInfo.ID]) {
        personVC.isMe = YES;
    } else {
        personVC.isMe = NO;
    }
    personVC.fid = userInfo.ID;
    
    [self.navigationController pushViewController:personVC animated:YES];
    
}

#pragma mark - request

- (void)loadNewData {
    
    // 1.拼接参数
    self.page = 0;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%ld", (long)self.page];
    parameters[@"fid"] = self.fid;

    SJRequest *api = nil;
    if (self.isFollowed) {
        api = [[SJMyFollowedApi alloc] initWithParameters:parameters];
    } else {
        api = [[SJMyFollowApi alloc] initWithParameters:parameters];
    }
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            self.dataArray = [[NSArray modelArrayWithClass:[SJUserInfoItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
        } else {
            [self.dataArray removeAllObjects];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            self.dataArray = [[NSArray modelArrayWithClass:[SJUserInfoItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
        } else {
            [self.dataArray removeAllObjects];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        
    }];
}

- (void)loadMoreData {
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    parameters[@"fid"] = self.fid;
    
    SJRequest *api = nil;
    if (self.isFollowed) {
        api = [[SJMyFollowedApi alloc] initWithParameters:parameters];
    } else {
        api = [[SJMyFollowApi alloc] initWithParameters:parameters];
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJUserInfoItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
        } else {
            self.page--;
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}


@end

